import 'package:check_app/dao/version_dao.dart';
import 'package:check_app/scoped_model/app_model.dart';
import 'package:check_app/util/pref_util.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:package_info/package_info.dart';
import 'package:scoped_model/scoped_model.dart';

class UpdaterPage extends StatefulWidget {
  final Widget child;
  const UpdaterPage(this.child);
  @override
  UpdatePagerState createState() => UpdatePagerState();
}

class UpdatePagerState extends State<UpdaterPage> {
  String currentVersion;
  int id;
  String version;
  String remark;
  String downloadUrl;

  @override
  void initState() {
    super.initState();
    checkVersion();
    getVersion();
  }

  //当前版本号
  checkVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String _currentVersionCode = packageInfo.version;
    setState(() {
      currentVersion = _currentVersionCode;
    });
    ScopedModel.of<GlobalModel>(context)
        .setCurrentVersion(_currentVersionCode.toString());
  }

  // 获取最新版本
  Future<Null> getVersion() async {
    try {
      var result = await VersionDao.fetch();
      if (result.success) {
        setState(() {
          id = result.data.id;
          version = result.data.version;
          remark = result.data.remark;
          downloadUrl = result.data.downloadUrl;
        });
        // showUploadDiglog();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
    }
    return null;
  }

  // 显示提示框
  showUploadDiglog() async {
    if (version != currentVersion) {
      final result2 =
          await PrefUtil().openAlertDialog(context, '检测到新版本，是否立即更新？');
      if (result2 == 'ok') {
        print(downloadUrl);
      }
    }
  }

  @override
  Widget build(BuildContext context) => widget.child;
}
